package com.zxx.ssm.controller;

import com.github.pagehelper.PageInfo;
import com.zxx.ssm.dao.Employee;
import com.zxx.ssm.dao.EmployeeExample;
import com.zxx.ssm.dao.Leaves;
import com.zxx.ssm.dao.LeavesExample;
import com.zxx.ssm.exception.AbstractServiceRuntimeException;
import com.zxx.ssm.model.biz.LeavesBiz;
import com.zxx.ssm.model.convertor.LeavesConvertor;
import com.zxx.ssm.model.enums.ResultCode;
import com.zxx.ssm.model.form.LeavesForm;
import com.zxx.ssm.model.result.BizResponse;
import com.zxx.ssm.service.EmployeeService;
import com.zxx.ssm.service.LeavesService;
import com.zxx.ssm.util.DateUtils;
import com.zxx.ssm.util.PaginationUtil;
import com.zxx.ssm.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by zxx on 2016/12/6.
 */
@RestController
@RequestMapping("leaves")
public class LeavesController {
    @Autowired
    private LeavesService leavesService;

    @Autowired
    private EmployeeService employeeService;

    @RequestMapping(value = "", method = RequestMethod.GET)
    @ResponseBody
    public BizResponse getAll(@ModelAttribute LeavesForm leavesForm, @RequestParam(defaultValue = "1") int pageNumber, @RequestParam(defaultValue = "1") int pageSize,
                              @RequestParam(defaultValue = "id") String sort, @RequestParam(defaultValue = "desc") String order) {
        PaginationUtil.preset(pageNumber, pageSize, sort, order);
        leavesForm.setStartTime(DateUtils.convertString(leavesForm.getStartTime()));
        leavesForm.setEndTime(DateUtils.convertString(leavesForm.getEndTime()));
        List<LeavesBiz> leavesBizList = leavesService.getAll(leavesForm);
        PageInfo pageInfo = new PageInfo(leavesBizList);
        BizResponse bizResponse = new BizResponse();
        bizResponse.put("leaves", pageInfo);
        return bizResponse;
    }

    @RequestMapping(value = "", method = RequestMethod.POST)
    @ResponseBody
    public BizResponse addLeaves(@ModelAttribute LeavesForm leavesForm) {
        EmployeeExample employeeExample = new EmployeeExample();
        employeeExample.createCriteria().andCodeEqualTo(leavesForm.getEmployeeCode());
        List<Employee> employeeList = employeeService.selectByExample(employeeExample);
        if (employeeList.size() > 0) {
            int leftDay = leavesService.getLeftDay(employeeList.get(0).getId(), leavesForm.getType());
            leavesForm.setEmployeeId(employeeList.get(0).getId());
            Leaves leaves = LeavesConvertor.convertLeavesForm(leavesForm);
            int days = (int) ((leaves.getEndTime().getTime() - leaves.getStartTime().getTime()) / (1000 * 60 * 60 * 24));
            if (leftDay < days)
                return new BizResponse(ResultCode.LEAVES_DAY_NOT_ENOUGH);
            else {
                leavesService.insertSelective(leaves);
                return new BizResponse();
            }
        } else
            return new BizResponse(ResultCode.EMPLOYEE_TYPE_NOT_EXIST);
    }

    @RequestMapping(value = "", method = RequestMethod.PUT)
    @ResponseBody
    public BizResponse updateLeaves(@ModelAttribute LeavesForm leavesForm) {
        EmployeeExample employeeExample = new EmployeeExample();
        employeeExample.createCriteria().andCodeEqualTo(leavesForm.getEmployeeCode());
        List<Employee> employeeList = employeeService.selectByExample(employeeExample);
        leavesForm.setEmployeeId(employeeList.get(0).getId());
        Leaves leaves = LeavesConvertor.convertLeavesForm(leavesForm);
        int leftDay = leavesService.getLeftDay2(leavesForm.getId(), employeeList.get(0).getId(), leavesForm.getType());
        int days = (int) ((leaves.getEndTime().getTime() - leaves.getStartTime().getTime()) / (1000 * 60 * 60 * 24));
        if (leftDay < days)
            return new BizResponse(ResultCode.LEAVES_DAY_NOT_ENOUGH);
        else {
            LeavesExample leavesExample = new LeavesExample();
            leavesExample.createCriteria().andIdEqualTo(leaves.getId());
            if (leavesService.updateByExample(leaves, leavesExample) > 0)
                return new BizResponse();
            else
                return new BizResponse(ResultCode.LEAVES_TYPE_UPDATE_ERROR);
        }
    }

    @RequestMapping(value = "/{strid}", method = RequestMethod.DELETE)
    @ResponseBody
    public BizResponse removeLeaves(@PathVariable("strid") String strid) {
        if (strid != null) {
            String[] idList = strid.split(",");
            for (int i = 0; i < idList.length; i++) {
                try {
                    Integer id = Integer.parseInt(idList[i]);
                    if (id != null)
                        leavesService.delete(id);
                } catch (AbstractServiceRuntimeException e) {
                    e.printStackTrace();
                    return new BizResponse(ResultCode.LEAVES_TYPE_DELETE_ERROR);
                }
            }
        }
        return new BizResponse();
    }

    @RequestMapping(value = "getTodayLeaves", method = RequestMethod.GET)
    @ResponseBody
    public BizResponse getTodayLeaves(){
        String date = DateUtils.curDateStr();
        List<LeavesBiz> leavesBizList = leavesService.getTodayLeaves(date);
        BizResponse bizResponse = new BizResponse();
        bizResponse.put("leaves", leavesBizList);
        return bizResponse;
    }

    @RequestMapping(value = "getNumberOfMonth", method = RequestMethod.GET)
    @ResponseBody
    public BizResponse getNumberOfMonth(HttpServletRequest request){
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_MONTH, 1);
        Date firstDate = cal.getTime();

        Calendar cal2 = Calendar.getInstance();
        cal2.set(Calendar.DAY_OF_MONTH, cal2.getActualMaximum(Calendar.DAY_OF_MONTH));
        Date lastDate = cal2.getTime();
        HttpSession session = request.getSession();
        Employee user = (Employee) session.getAttribute("user");
        LeavesExample leavesExample = new LeavesExample();
        LeavesExample.Criteria criteria = leavesExample.createCriteria();
        criteria.andEmployeeIdEqualTo(user.getId());
        criteria.andStartTimeGreaterThanOrEqualTo(firstDate);
        criteria.andStartTimeLessThanOrEqualTo(lastDate);
        List<Leaves> leavesList = leavesService.selectByExample(leavesExample);
        BizResponse bizResponse = new BizResponse();
        bizResponse.put("number", leavesList.size());
        return bizResponse;
    }
}
